package org.goyo.main.web.controller.pur;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.utils.DateUtils;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.comet4j.Comet4jConfig;
import org.goyo.main.domain.entity.pur.PurOrder;
import org.goyo.main.domain.entity.pur.PurOrderEntry;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.comet4j.IComet4jService;
import org.goyo.main.services.pur.IPurOrderService;
import org.goyo.main.web.controller.BaseController;
import org.goyo.main.web.controller.system.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 采购订单
 * 
 * @author chenchuan
 * 2014年11月12日
 */
@Controller
@RequestMapping("/purOrder")
public class PurOrderController extends BaseController  {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private IPurOrderService purOrderService;
	
	@Resource
	private IComet4jService comet4jService;
	/**
	 * 列表界面
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/toPurOrderList")
	public String toPurOrderList(Model model){
		logger.info("----------------------");
		return "/pur/PurOrderList";
	}
	
	/**
	 * 保存或者更新
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/saveOrUpdatePurOrder")
	@ResponseBody
	public AjaxResult saveOrUpdatePurOrder(HttpServletRequest request){
		
		AjaxResult result = null;
		try{
			String form = request.getParameter("formData");
			String delData = request.getParameter("delData");
			PurOrder purOrder = JSONUtil.json2Obj(form, PurOrder.class);
			Object[] delUuids = null;
			if(delData != null &&!"null".equals(delData) &&!"undefined".equals(delData)){
				JSONArray delArray = JSONArray.fromObject(delData);
				List<PurOrderEntry> delEntry = JSONArray.toList(delArray, PurOrderEntry.class);
				delUuids = ToolUtils.getFiles(delEntry,"uuid").toArray();
			}
			PurOrder info = purOrderService.saveOrUpdateInfo(purOrder, delUuids,getCurrentUser());
			info.setEntrys(null);
			result = result.resultSuccess("保存成功", info);
		}catch(Exception e){
		    result = AjaxResult.resultFail("保存失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 提交数据
	 * 
	 * @author chenchuan
	 * 2014年11月16日
	 */
	@RequestMapping("/submitPurOrder")
	@ResponseBody
	public AjaxResult submitPurOrder(HttpServletRequest request){
		AjaxResult result = null;
		Object[] uuids = null;
		
		String rows = request.getParameter("rows");
		try{
			if(rows != null && !"".equals(rows)){
				JSONArray jsonarray = JSONArray.fromObject(rows);
				List<PurOrder> list = (List<PurOrder>)JSONArray.toCollection(jsonarray, PurOrder.class);
				uuids = ToolUtils.getFiles(list, "uuid").toArray();
			}else{
				String uuid = request.getParameter("uuid");
				uuids = new Object[]{uuid};
			}
			PurOrder info  = purOrderService.submitByUuids(uuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("提交成功", info);
			comet4jService.sendTaskInfo(Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL,1l);
		}catch(Exception e){
		    result = AjaxResult.resultFail("提交失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 审核数据
	 * 
	 * @author chenchuan
	 * 2014年11月16日
	 */
	@RequestMapping("/auditPurOrder")
	@ResponseBody
	public AjaxResult auditPurOrder(HttpServletRequest request){
		AjaxResult result = null;
		Object[] uuids = null;
		
		String rows = request.getParameter("rows");
		try{
			if(rows != null && !"".equals(rows)){
				JSONArray jsonarray = JSONArray.fromObject(rows);
				List<PurOrder> list = (List<PurOrder>)JSONArray.toCollection(jsonarray, PurOrder.class);
				uuids = ToolUtils.getFiles(list, "uuid").toArray();
			}else{
				String uuid = request.getParameter("uuid");
				uuids = new Object[]{uuid};
			}
			PurOrder info = purOrderService.auditByUuids(uuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("审核成功", info);
			comet4jService.sendTaskInfo(Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL,-1l);
		}catch(Exception e){
		    result = AjaxResult.resultFail("审核失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 反审核数据
	 * 
	 * @author chenchuan
	 * 2014年11月16日
	 */
	@RequestMapping("/unAuditPurOrder")
	@ResponseBody
	public AjaxResult unAuditPurOrder(HttpServletRequest request){
		AjaxResult result = null;
		Object[] uuids = null;
		
		String rows = request.getParameter("rows");
		try{
			if(rows != null && !"".equals(rows)){
				JSONArray jsonarray = JSONArray.fromObject(rows);
				List<PurOrder> list = (List<PurOrder>)JSONArray.toCollection(jsonarray, PurOrder.class);
				uuids = ToolUtils.getFiles(list, "uuid").toArray();
			}else{
				String uuid = request.getParameter("uuid");
				uuids = new Object[]{uuid};
			}
			PurOrder info = purOrderService.unAuditByUuids(uuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("反审核成功", info);
		}catch(Exception e){
			result = AjaxResult.resultFail("反审核失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	
	/**
	 * 删除
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/delPurOrder")
	@ResponseBody
	public AjaxResult delPurOrder(HttpServletRequest request){
		AjaxResult result = null;
		String rows = request.getParameter("rows");
		try{
			JSONArray jsonarray = JSONArray.fromObject(rows);
//			List<PurOrder> list = (List<PurOrder>)JSONArray.toCollection(jsonarray, PurOrder.class);
			purOrderService.delByUuids(jsonarray.toArray());
			result = AjaxResult.resultSuccess("删除成功", null);
		}catch(Exception e){
			result = AjaxResult.resultFail("删除失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 查看
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/viewPurOrder")
	public String viewPurOrder(HttpServletRequest request,Model model){
		String uuid = request.getParameter("uuid");
		PurOrder info = null;
		try {
			info = purOrderService.findByUuuid(uuid);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		model.addAttribute("info", JSONObject.fromObject(info, jsonConfig));
		model.addAttribute("editStatus", Constants.VIEW);
		return "/pur/PurOrderEdit";
	}
	
	/**
	 * 修改
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/alterPurOrder")
	public String alterPurOrder(HttpServletRequest request,Model model){
		String uuid = request.getParameter("uuid");
		PurOrder info = null;
		try {
			info = purOrderService.findByUuuid(uuid);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		model.addAttribute("info", JSONObject.fromObject(info, jsonConfig));
		model.addAttribute("editStatus", Constants.EDIT);
		return "/pur/PurOrderEdit";
	}
	
	/**
	 * 添加
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/addPurOrder")
	public String addPurOrder(HttpServletRequest request,Model model){
		PurOrder info = new PurOrder();
		//获取登陆用户
		SysUser user = (SysUser) SessionUtil.getAttribute("user");
		info.setCreateDate(DateUtils.getCurrentDate());
		info.setCreateUser(user);
		info.setAlterDate(DateUtils.getCurrentDate());
		info.setDepGroup(user.getDepGroup());
		info.setAlterUser(user);
		info.setStatus(Constants.NEWSTATUS);
		info.setPurPerson(user);
		info.setNumber(getBillNumber(PurOrder.BIZTYPE));
		model.addAttribute("info",JSONUtil.obj2Json(info));
		model.addAttribute("editStatus", Constants.NEW);
		return "/pur/PurOrderEdit";
	}
	
	
	@RequestMapping("/listEntryData")
	@ResponseBody
	public String listEntryData(HttpServletRequest request){
		JSONObject data = null;
		//分页条件
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		
		String where = request.getParameter("where"); 
		//分页器
		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		try {
			pager = purOrderService.findByEntryCondition(where, pager);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Rows", pager.getList());
			map.put("Total", pager.getCount());
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			data =JSONObject.fromObject(map, jsonConfig);
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		} 
		return data.toString();
	}
	
	/**
	 * list列表数据加载
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public String ListData(HttpServletRequest request){
		JSONObject data = null;
		//分页条件
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		String where = request.getParameter("where");
		//当前登录用户
		SysUser user = getCurrentUser();
		List<SysDepGroup> groups = getUserDepGroup(user);
		Object[] groupUuids = ToolUtils.getFiles(groups,"uuid") == null ? null : ToolUtils.getFiles(groups,"uuid").toArray();
		//分页器
		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		try {
			pager = purOrderService.findByCondition(where, pager,groupUuids);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Rows", pager.getList());
			map.put("Total", pager.getCount());
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			data = JSONObject.fromObject(map,jsonConfig);
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		} 
		return data.toString();
	}
	

}
